//
//  ReimbursementTableViewController.m
//  TenThousand
//
//  Created by 我的 on 16/6/24.
//  Copyright © 2016年 baixue. All rights reserved.
//

#import "ReimbursementTableViewController.h"
#import "ReimbursementHeaderCell.h"
#import "PayListTableViewCell.h"
#import "MyReimbursementViewController.h"
#import "ReimburModel.h"

@interface ReimbursementTableViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) NSMutableArray *reArr;
@property (nonatomic, strong) NSMutableArray    *seletedArr;
@property (nonatomic, strong) NSMutableArray *indexPathArrM;
@end
static NSInteger currentPage = 1;
@implementation ReimbursementTableViewController
{
    float money;
}

//存放还款计划列表的页面
-(NSMutableArray *)reArr{
    if (!_reArr) {
        _reArr = [NSMutableArray array];
    }
    return _reArr;
}

- (NSMutableArray *)indexPathArrM {
    if (!_indexPathArrM) {
        _indexPathArrM = [NSMutableArray array];
    }
    return _indexPathArrM;
}

- (BorrowModel *)boModel {
    if (!_boModel) {
        _boModel = [[BorrowModel alloc] init];
    }
    return _boModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.seletedArr = [NSMutableArray array];
    
    self.navigationItem.title = @"我要还款";
    [self createLeft:[UIImage imageNamed:@"ZHSZicon_03"] leftClick:^{
        [self.navigationController popViewControllerAnimated:YES];
    } right:nil rightClick:nil];
    [self.view addSubview:self.myTableView];
    [self refresh];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.seletedArr removeAllObjects];
    [self.indexPathArrM removeAllObjects];
    [self.reArr removeAllObjects];
    [self getBorrowListPlan:1];
}

- (UITableView *)myTableView{
    if (!_myTableView) {
        _myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, Screen_Height-64) style:UITableViewStylePlain];
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
        _myTableView.showsVerticalScrollIndicator = NO;
        _myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _myTableView;
}



#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.reArr.count+1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        ReimbursementHeaderCell *reimburseCell = [tableView dequeueReusableCellWithIdentifier:@"REIMBURSECELL"];
        if (reimburseCell == nil) {
            reimburseCell = [[[NSBundle mainBundle] loadNibNamed:@"ReimbursementHeaderCell" owner:nil options:nil]lastObject];
        }
        

        if (self.index == 2) {
            NSString *str = @"%";
            reimburseCell.progectName.text = [NSString stringWithFormat:@"%@%@",_boModel.PrjectName,_boModel.Code];//项目名称
            reimburseCell.maxPrice.text = [NSString stringWithFormat:@"借款金额:%@元",_boModel.Amount];//借款金额
            reimburseCell.totaljiekuanlixi.text = [NSString stringWithFormat:@"借款利息:%.2f元",[_boModel.interest floatValue]];//借款利息
            reimburseCell.Bpay.hidden = YES;
            reimburseCell.Ratejiekuan.text = [NSString stringWithFormat:@"%.2f%@",[_boModel.Rate floatValue],str];//年利率
            reimburseCell.TeamYear.text = [NSString stringWithFormat:@"%@",_boModel.Tearm];//期限
            reimburseCell.AddTime.text = [NSString stringWithFormat:@"%@",_boModel.AddDate];//投标时间
            reimburseCell.state.text = [NSString stringWithFormat:@"%@", _boModel.Sate];
        }else {
            
            NSString *str = @"%";
            reimburseCell.progectName.text = [NSString stringWithFormat:@"%@%@",_boModel.PrjectName,_boModel.Code];//项目名称
            reimburseCell.maxPrice.text = [NSString stringWithFormat:@"借款金额:%.2f元",[_boModel.MaxPrice doubleValue]];//借款金额
            reimburseCell.totaljiekuanlixi.text = [NSString stringWithFormat:@"借款利息:%.2f元",[_boModel.Totaljiekuanlixi floatValue]];//借款利息
            reimburseCell.Bpay.text = [NSString stringWithFormat:@"%@",_boModel.Bpay];//还款方式
            reimburseCell.Ratejiekuan.text = [NSString stringWithFormat:@"%.2f%@",[_boModel.Ratejiekuan floatValue],str];//年利率
            reimburseCell.TeamYear.text = [NSString stringWithFormat:@"%@",_boModel.TeamYear];//期限
            reimburseCell.AddTime.text = [NSString stringWithFormat:@"%@",_boModel.AddTime];//投标时间
            reimburseCell.state.text = [NSString stringWithFormat:@"%@", _boModel.PaySate];
        }
        if (self.index == 2) {
            reimburseCell.huanKuanBtn.hidden = YES;
        }
        reimburseCell.selectionStyle = UITableViewCellSelectionStyleNone;

        //点击我要还款按钮跳转
        
        reimburseCell.Reimbursement = ^(){
            if (self.seletedArr.count == 0) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请选择要还款的选项" delegate: nil cancelButtonTitle:@"确定" otherButtonTitles: nil, nil];
                [alert show];
                return;
            }else {
                money = 0;
                for (ReimburModel *model in self.seletedArr) {
                    
                    money = money + [model.total floatValue];
                    
                }
                
                NSString *loginId = [[NSUserDefaults standardUserDefaults] objectForKey:@"LoginId"];
                NSString *pay = [NSString stringWithFormat:@"%.2f", money];
                NSString* date;
                NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
                [formatter setDateFormat:@"YYYYMMddhhmmss"];
                date = [formatter stringFromDate:[NSDate date]];
                
//                NSString *request = [NSString stringWithFormat:@"_%@%@",date,loginId];
                NSString *request = @"";
                for (ReimburModel *model in self.seletedArr) {
                    request = [request stringByAppendingString:[NSString stringWithFormat:@"%@_", model.PayId]];
                }
                
                request = [request stringByAppendingString:@"0000"];
                NSDictionary *dic = @{
                                      @"requestType":@"PFT0007",
                                      @"requestId":request,
                                      @"merchantCode":FengFuMerchantCode,
                                      @"userIdIdentity":loginId,
                                      @"projectCode":_boModel.BorrowId,//项目编号//_model.Code
                                      @"sum":pay,//还款金额
                                      @"giftFlag":@"",//红包标识
                                      @"subledgerList":@"",//分账列表
                                      @"noticeUrl":[NSString stringWithFormat:@"%@API/notice/huankuannotice.aspx", noticeUrl],
                                      @"successReturnUrl":@"",
                                      @"failReturnUrl":@"",
                                      };
                NSString *sign = [[[[[[[[[[dic[@"requestType"] stringByAppendingString:dic[@"requestId"]] stringByAppendingString:dic[@"merchantCode"]] stringByAppendingString:dic[@"userIdIdentity"]] stringByAppendingString:dic[@"projectCode"]] stringByAppendingString:dic[@"sum"]] stringByAppendingString:dic[@"giftFlag"]] stringByAppendingString:dic[@"subledgerList"]] stringByAppendingString:dic[@"noticeUrl"]] stringByAppendingString:dic[@"successReturnUrl"]] stringByAppendingString:dic[@"failReturnUrl"]];
                
                NSString *signature = [HMACMD5 HMACMD5WithString:sign WithKey:FengFuKEY];
                NSDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:dic];
                [dict setValue:signature forKey:@"signature"];
                [SumaPaySDK startService:dict callback:^(id resultDic, NSError *error) {
                    NSLog(@"%@--------------%@", resultDic, error);
                    NSDictionary *dic = [NetWorkManager dictionaryWithJsonString:resultDic];
                    NSString *result = dic[@"result"];
                    if ([result isEqualToString:@"0"]) {
                        NSString *resulT = dic[@"msg"][@"result"];
                        if ([resulT isEqualToString:@"00000"]) {

                            for (int l = 0; l < _seletedArr.count; l++) {
                                
                                ReimburModel *model = [_seletedArr objectAtIndex:l];
                                float ppp = [model.Totaljiekuanlixi floatValue] + [model.MaxPrice floatValue];
                                NSString *ddd = [NSString stringWithFormat:@"%.2f",ppp];
                                NSDictionary *houtaishishabi = @{@"PayId":model.PayId,@"ProjectCode":model.Borrowid,@"Amount":ddd};
                            
                                [NetWorkManager requestWithType:HttpRequestTypePost withMethodName:@"Borrow.GetBorrowUsersPay" withParaments:houtaishishabi withSuccessBlock:^(NSDictionary *object) {
                                    
                                    NSLog(@"%@",object);
                                    if ([object[@"Code"] integerValue] == 00000) {
                            
                                        [self getBorrowListPlan:1];
                                        
                                    }
                                } withFailureBlock:^(NSError *error) {
                                    NSLog(@"%@", error);
                                } progress:^(float progress) {
                                    
                                }];
                            }
                        }
                        
                    }
                }];
            }
        };
        return reimburseCell;
    }
    else{
        PayListTableViewCell *paylistCell = [tableView dequeueReusableCellWithIdentifier:@"PAYLISTCELL"];
        if (paylistCell == nil) {
            paylistCell = [[[NSBundle mainBundle] loadNibNamed:@"PayListTableViewCell" owner:nil options:nil] lastObject];
            
            //cell添加阴影
            paylistCell.layer.shadowOffset =CGSizeMake(0, 1);
            paylistCell.layer.shadowColor = [UIColor grayColor].CGColor;
            paylistCell.layer.shadowRadius = 1;
            paylistCell.layer.shadowOpacity = .5f;
        }
     
           paylistCell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (self.reArr.count) {
            ReimburModel *model = self.reArr[indexPath.row-1];
            [paylistCell setDataWithModel:model];
            [paylistCell setSelect:[self.indexPathArrM[indexPath.row - 1][@"select"] boolValue]];
        }
       
        if (self.index == 2) {
            paylistCell.theSelected.hidden = YES;
        }
        
        
        
        return paylistCell;
    }
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        return 190;
    }
    return 95;
}


//还款计划列表
-(void)getBorrowListPlan:(NSInteger)pageIndex{
            
        NSString *loginId = [[NSUserDefaults standardUserDefaults] objectForKey:@"LoginId"];//用户名
    NSString *strBorrowid;
    
    if (self.index == 2) {
        
        strBorrowid = _boModel.Borrowid;
        
    }else{
        strBorrowid = _boModel.BorrowId;
    }
    
    NSDictionary *para = @{
                           @"LoginId":loginId,
                           @"Borrowid":strBorrowid,
                           @"PageIndex":[NSString stringWithFormat:@"%ld", pageIndex]
                           };
    
        [NetWorkManager requestWithType:HttpRequestTypePost withMethodName:@"Borrow.GetBorrowListPlan" withParaments:para withSuccessBlock:^(NSDictionary *object) {
            NSLog(@"%@",object);
            NSArray *arr = [object[@"Data"] firstObject][@"List"];
            if (pageIndex == 1) {
                currentPage = 1;
                [self.reArr removeAllObjects];
                [self.indexPathArrM removeAllObjects];
                [self.seletedArr removeAllObjects];
            }
            for (NSDictionary *dic in arr) {
                ReimburModel *model = [ReimburModel mj_objectWithKeyValues:dic];
                [self.reArr addObject:model];
                if ([model.Sate isEqualToString:@"已结清"]) {
                    NSDictionary *dic = @{@"select":@"YES"};
                    [self.indexPathArrM addObject:dic];
                } else {
                    NSDictionary *dic = @{@"select":@"NO"};
                    [self.indexPathArrM addObject:dic];
                }
                NSLog(@"%@",_model.BorrowId);

            }
            [self.myTableView reloadData];
        } withFailureBlock:^(NSError *error) {
            NSLog(@"%@",error);
        } progress:nil];
    
   
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
     PayListTableViewCell *cell = (PayListTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    if (indexPath.row == 0) {
        return;
    }
    if ([[[self.reArr objectAtIndex:indexPath.row - 1] Sate] isEqualToString:@"已结清"]) {
        return;
    }
    
    NSUInteger row = [indexPath row];
    NSMutableDictionary *dic = [self.indexPathArrM objectAtIndex:row - 1];
    if ([[dic objectForKey:@"select"] isEqualToString:@"NO"]) {
        [self.indexPathArrM replaceObjectAtIndex:row - 1 withObject:@{@"select":@"YES"}];
        [_seletedArr addObject:[_reArr objectAtIndex:indexPath.row - 1]];
        [cell setSelect:YES];
        NSLog(@"------------%@", self.indexPathArrM);
        NSLog(@"%ld,%ld",_seletedArr.count,_reArr.count);
        NSLog(@"%@,%@",_seletedArr,_reArr);
    }else{
        [self.indexPathArrM replaceObjectAtIndex:row - 1 withObject:@{@"select":@"NO"}];
        [_seletedArr removeObject:[_reArr objectAtIndex:indexPath.row - 1]];
        [cell setSelect:NO];
        NSLog(@"------------%@", self.indexPathArrM);
        NSLog(@"%ld,%ld",_seletedArr.count,_reArr.count);
        NSLog(@"%@,%@",_seletedArr,_reArr);
    }
    
    
    
}

//MJ刷新
-(void)refresh
{
    
    //下拉刷新
    self.myTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^
                                      {
                                          
                                          [self getBorrowListPlan:1];
                                          
                                          [self.myTableView.mj_header endRefreshing];
                                      }];
    //上拉加载
    self.myTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{

        
        [self getBorrowListPlan:++currentPage];
        
        [self.myTableView.mj_footer endRefreshing];
    }];
    
    
}

//- (void)prepareForReuse
//{
//    [super prepareForReuse];
//}


@end
